<template>
  <div ref="pageComBox" class="NewCustomer page_wrapper">
    <div ref="otherBox">
    <Params ref="params" @search="customerWaitPage" />

    <el-row type="flex" justify="space-between" class="mb-3">
      <el-col :xs="12">
        <el-button
          type="primary"
          size="small"
          :loading="assistLoading"
          :disabled="assistDisabled"
          @click="assistHandle"
          >分配</el-button
        >
      </el-col>
    </el-row>
  </div>

    <el-table
    ref="multipleTable"
      :data="dataList"
      style="width: 100%"
      :row-class-name="$getTableClass"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="加载中..."
      @sort-change="sortChange"
      :max-height="tableHeight"
      :key="tableHeight"
      v-tabscroll="$getTableHeight"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="客户信息" width="140">
        <template slot-scope="{ row }">
          <tab-user :user="row" :list="dataList" v-if="row"></tab-user>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="name" label="姓名" :width="sortTdWidth">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" :width="smallWidth">
      </el-table-column>
      <el-table-column label="性别" :width="sortTdWidth">
        <template slot-scope="{row}">
          {{SEXTYPELIST[row.sex]}}
        </template>
      </el-table-column> -->
      <el-table-column prop="age" label="年龄" :width="sortTdWidth">
      </el-table-column>
      <!-- <el-table-column prop="city" label="城市" :width="sortTdWidth">
      </el-table-column> -->
      <el-table-column prop="media" label="媒体" :width="sortTdWidth">
      </el-table-column>
      <el-table-column label="状态" :width="sortTdWidth">
        <template slot-scope="{ row }">
          {{ showFollowProcess(row.progress) }}
        </template>
      </el-table-column>
      <el-table-column prop="employee.name" label="持有人" :width="80">
      </el-table-column>
      <!-- <el-table-column label="通话状态" width="80">
        <template slot-scope="{row}">
          {{PASSOPTIONSSTATUSLIST[row.call]}}
        </template>
      </el-table-column> -->
      <el-table-column label="客户标签" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item, index) in getTagList(row.label)"
            class="tab_el_tag"
            size="mini"
            :key="index"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="公共池" :width="80">
        <template slot-scope="{row}">
          <public-poll :id="row.publicPool" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="条件备注" :width="longTdWidth">
        <template slot-scope="{ row }">
          <condition-remark :list="getTagList(row.remark, ';')" />
        </template>
      </el-table-column>
      <el-table-column label="跟进记录" :width="longTdWidth">
        <template slot-scope="scope">
          <el-popover placement="left-end" trigger="hover" width="500">
            <div class="remarkBox">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in scope.row.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <div class="remarkList" slot="reference">
              <div
                class="item"
                :class="{ hide: index > 2 }"
                v-for="(item, index) in scope.row.remarkList"
                :key="index"
              >
                <div class="remark">{{ cutWordLength(item.remark,'17')  }}</div>
                <div class="createBy pl-3">{{ item.createBy }}</div>
                <div class="updateDate ml-3">{{ item.updateDate }}</div>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未跟进时间" :width="100">
        <template slot-scope="scope">
          <div class="red">{{ scope.row.days }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createDate" label="最后备注日期" :width="tdWidth" />
      <el-table-column prop="createDate" label="入库时间" :width="tdWidth" />
      <el-table-column prop="distributeDate" label="分配日期" :width="tdWidth" /> -->
      <el-table-column
        prop="remarkDate"
        label="最后备注日期"
        sortable="remark_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="createDate"
        label="入库时间"
        sortable="create_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="distributeDate"
        label="分配时间"
        sortable="distribute_date"
        :width="tdWidth"
      />
    </el-table>

    <BasePagination
      v-model="page"
      :total="totalCount"
      :pageSize="pageSize"
      @change="pageOnChange"
    />
    <el-dialog
      title="分配"
      width="30%"
      :visible.sync="chooseDialogVisi"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="门店">
          <el-select
            v-model="shopId"
            @change="shopSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in shopOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队">
          <el-select
            v-model="teamId"
            :loading="teamSelectLoading"
            @change="teamSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in teamOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工">
          <el-select
            v-model="employeeId"
            :loading="employeeSelectLoading"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in employeeOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chooseDialogVisi = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="assistSubmitLoading"
          @click="assistSubmit"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Params from "@/components/common/params.vue";
import {
  customerWaitPage,
  employeeList,
  customerDistribute,
  shopList,
  allTeamList,
  getEmployee,
} from "@/api/customer";
import { followUpOptions, startOptions, passOptions } from "./config";
import { mapState } from "vuex";
import { SEXTYPELIST, PASSOPTIONSSTATUSLIST } from "@/common/constants";
import TabUser from "@/components/user";
import { showFollowProcess, getTagList, received } from "@/utils/util";
export default {
  components: { Params, TabUser },
  data() {
    return {
      fieldList: [],
      page: 1,
      pageSize: 100,
      dataList: [],
      totalCount: 0,
      form: {},
      followUpOptions,
      startOptions,
      passOptions,
      value1: "",
      selectItem: {},
      input: "",
      assistLoading: false,
      assistDisabled: true,
      chooseDialogVisi: false,
      updateLoading: false,
      employeeList: [],
      helpEmployeeId: "",
      assistSubmitLoading: false,
      shopId: "",
      teamId: "",
      employeeId: "",
      shopOptionList: [],
      teamOptionList: [],
      employeeOptionList: [],
      teamSelectLoading: false,
      employeeSelectLoading: false,
      sortTdWidth: 56,
      smallWidth: 110,
      tdWidth: 160,
      longTdWidth: 500,
      SEXTYPELIST,
      showFollowProcess: (str) => showFollowProcess(str),
      getTagList: (str, id) => getTagList(str, id),
      PASSOPTIONSSTATUSLIST,
      loading: false,
      tableHeight:0
    };
  },
  mounted() {
    this.shopList();
    this.fieldList = JSON.parse(JSON.stringify(this.fieldList1));
    received("update.success", this.customerWaitPage);
    // 计算表格的高度
    let _this = this
    this.$getTableHeight();
    window.onresize = function () {
      _this.$getTableHeight();
    };
  },
  computed: {
    ...mapState({
      fieldList1: (state) => state.myClient.fieldList,
    }),
  },
  watch: {
    fieldList1(val) {
      this.fieldList = JSON.parse(JSON.stringify(val));
    },
  },
  methods: {
    async customerWaitPage(form) {
      this.showAppLoading();
      try {
        this.loading = true;
        await customerWaitPage({
          page: this.page,
          size: this.pageSize,
          paramObject: { ...form },
        }).then((res) => {
          this.loading = false;
          const { data } = res;
          this.dataList = data.dataList || [];
          this.totalCount = data.totalCount;
          this.dataList.forEach((element) => {
            if (element.id === this.selectItem.id) {
              this.selectItem = element;
            }
          });
          this.$nextTick(() => {
            let index = 0;
            const list = document.querySelectorAll("tr");
            const tbody = document.querySelector("tbody");
            const comment = tbody.getElementsByClassName("comment");
            for (let index1 = comment.length - 1; index1 >= 0; index1--) {
              const element = comment[index1];
              element.remove();
            }
            list.forEach((dom) => {
              if (dom.classList.contains("el-table__row")) {
                if (this.dataList[index].comment) {
                  const div = document.createElement("div");
                  div.innerHTML = `主管点评：${this.dataList[index].comment}`;
                  div.classList.add("comment");
                  dom.parentNode.insertBefore(div, dom);
                }
                index++;
              }
            });
          });
        });
        this.hideAppLoading();
      } catch (error) {
        this.hideAppLoading();
      }
    },
    pageOnChange(row) {
      this.page = row.page;
      if (row.pageSize) {
        this.pageSize = row.pageSize;
      }
      this.$refs.params.search();
    },

    followUpHandle(item) {
      this.selectItem = Object.assign({}, item);
      this.dialogFormVisible = true;
    },
    handleSelectionChange(e) {
      this.assistDisabled = e.length === 0;
      this.idArr = e.map((element) => element.id);
    },

    async assistHandle() {
      employeeList().then((res) => {
        this.employeeList = res.data;
      });
      this.chooseDialogVisi = true;
    },
    async assistSubmit() {
      this.assistSubmitLoading = true;
      try {
        const form = {
          idList: this.idArr,
          shopId: this.shopId,
          teamId: this.teamId,
          employeeId: this.employeeId,
          distribute: 1,
        };
        await customerDistribute(form).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.$refs.params.search();
            this.chooseDialogVisi = false;
          }
        });
        this.assistSubmitLoading = false;
      } catch (error) {
        this.assistSubmitLoading = false;
      }
    },
    shopList() {
      shopList().then((res) => {
        this.shopOptionList = res.data;
      });
    },
    async shopSelectChange() {
      this.teamSelectLoading = true;
      this.teamId = "";
      this.employeeId = "";
      try {
        await allTeamList({ shopId: this.shopId }).then((res) => {
          this.teamOptionList = res.data;
        });
        this.teamSelectLoading = false;
      } catch (error) {
        this.teamSelectLoading = false;
      }
    },
    async teamSelectChange() {
      this.employeeSelectLoading = true;
      this.employeeId = "";
      try {
        await getEmployee({ shopId: this.shopId, teamId: this.teamId }).then(
          (res) => {
            this.employeeOptionList = res.data || [];
          }
        );
        this.employeeSelectLoading = false;
      } catch (error) {
        this.employeeSelectLoading = false;
      }
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      console.log(column);
      //this.formInline.orderField = prop;
      let str = `${column.sortable} asc`;
      if (order == "ascending") {
        str = `${column.sortable} asc`;
      } else {
        str = `${column.sortable} desc`;
      }
      this.$refs.params.setParams("sort", str);
      this.$refs.params.search();
      //this.getList();
    },
  },
};
</script>

<style>
.NewCustomer {
  padding: 20px;
}
.txt {
  padding: 8px 0;
}
.wrapping {
  margin-right: 10px;
  margin-bottom: 10px;
}
.btn {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}
</style>
